'''
Created on 2010-1-3

@author: wangyongtao
'''

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import os
import model
import logging
import utility

class DefaultHandler(utility.BaseRequestHandler):
    def get(self):
        apps_android = model.android.get_all_apps()
        apps_iphone = model.iphone.get_all_apps()
        self.generate("index.admin.html", {"app_name" : "Admin Console - Taobility Software",
                                          "apps_android": apps_android, 
                                          "apps_iphone": apps_iphone,})
        
class AppsHandler(utility.BaseRequestHandler):
    def get(self):
        apps_android = model.android.get_all_apps()
        apps_iphone = model.iphone.get_all_apps()
        self.generate("index.admin.html", {"app_name" : "App Management - Taobility Software",
                                          "apps_android": apps_android, 
                                          "apps_iphone": apps_iphone,})
        
class AndroidAppHandler(utility.BaseRequestHandler):
    def get(self, appname):
        logging.info("app name:%s"%appname)
        action = self.request.get("action", None)
        app = model.android.get_app(appname)
        title = "App Edit:%s"%app.displayname
        if action:
            action = action.lower()
        if action == "add":
            title = "Adding New App"
        if action == "active":
            active = self.request.get("active", "true")
            active = active.lower()
            val_active = True
            if active == "false":
                val_active = False
            if app.active != val_active:
                app.active = val_active
                app.put()
            self.redirect("/admin/apps")
        self.generate("app.admin.html", {"app_name": "%s - Taobility Software"%app.displayname,
                                             "title" : title, 
                                             "type": "android",
                                             "app": app,})
        
    def post(self, appname):
        val_displayname = self.request.get("field_displayname", None)
        val_icon = self.request.get("field_icon", None)
        val_logo = self.request.get("field_logo", None)
        val_desc = self.request.get("field_desc", None)
        val_package = self.request.get("field_package", None)
        val_versionmin = self.request.get("field_versionmin", None)
        app = model.android.get_app(appname) 
        if app:
            if val_displayname:
                app.displayname = val_displayname.strip()
            if val_icon:
                app.icon = db.Link(val_icon)
            if val_logo:
                app.logo = db.Link(val_logo)
            app.desc = val_desc
            app.package = val_package
            app.versionmin = int(val_versionmin)
            app.put()
            
        self.redirect("/admin/apps")

class IphoneAppHandler(utility.BaseRequestHandler):
    def get(self, appname):
        logging.info("app name:%s"%appname)
        app = model.iphone.get_app(appname)
        action = self.request.get("action", None)
        title = "App Edit:%s"%app.displayname
        if action == "add":
            title = "Adding New App"
        self.generate("app.admin.html", {"app_name": "App Admin - Taobility Software",
                                         "title" : title, })
        
class ScreenHandler(utility.BaseRequestHandler):
    def get(self, appname):
        logging.info("app name:%s"%appname)
        type = self.request.get("type", "android")
        type = type.lower()
        action = self.request.get("action", None)
        key = self.request.get("key", None)
        if action and key:
            if action.lower() == "delete":
                s = model.screen.get(key)
                if s:
                    s.delete()
        app = None
        if type == "android":
            app = model.android.get_app(appname)
        elif type == "iphone":
            app = model.iphone.get_app(appname)
        title = "App Screen for %s"%app.displayname  
        screens = app.get_screens()
        self.generate("screen.admin.html", {"app_name": "App Admin - Taobility Software",
                                         "title" : title,
                                         "type":type,
                                         "screens":screens, })
        
    def post(self, appname):
        logging.info("app name:%s"%appname)
        type = self.request.get("type", "android")
        type = type.lower()
        app = None
        if type == "android":
            app = model.android.get_app(appname)
        elif type == "iphone":
            app = model.iphone.get_app(appname)
        url = None
        width = None
        height = None
        photos = {}
        screens = app.get_screens()
        order = app.get_last_screen_order()+1
        for k,v in self.request.params.items():
            if k == 'field_url':
                url = v
            elif k == 'field_width':
                width = v
            elif k == 'field_height':
                height = v
            if url and width and height:
                photos[order] = {'url': url, 'width': width, 'height':height, 'order':order}
                url = None
                width = None
                height = None
                order = order+1
        logging.info('get items:%d'%len(photos.keys()))
        
        for k,v in photos.items():
            app.add_screen(v["url"], v["order"], width=v["width"], height=v["height"])
            
        self.redirect("/admin/apps")
        
class AddAppHandler(utility.BaseRequestHandler):
    def get(self):
        type = self.request.get("type", None)
        title = "Add %s App"%type
        self.generate("app.admin.html", {"app_name": "App Admin - Taobility Software",
                                         "title" : title, 
                                         "type": type.lower(),})
    def post(self):
        val_type = self.request.get("field_type", None)
        val_name = self.request.get("field_name", None)
        val_displayname = self.request.get("field_displayname", None)
        val_icon = self.request.get("field_icon", None)
        val_logo = self.request.get("field_logo", None)
        val_desc = self.request.get("field_desc", None)
        val_package = self.request.get("field_package", None)
        val_versionmin = self.request.get("field_versionmin", None)
        result = False
        msg = ""
        title = "Result"
        if val_type and val_name and val_icon and val_desc:
            result = True
            type = val_type.lower()
            if type == "android":
                app = model.android.add_app(val_name, val_displayname, val_icon, val_desc, val_logo, True, True, val_package)
                if app is not None:
                    result = True
                    msg = "Add Android App: %s Successful!"%val_name
                else:
                    msg = "Failed to add app, please try again"
        self.generate("app.admin.html", {"app_name": "App Admin - Taobility Software",
                                         "title" : title, 
                                         "result": result,
                                         "msg" : msg,
                                         "type": val_type,})
            

class SettingHandler(utility.BaseRequestHandler):
    def get(self):
        self.generate("setting.admin.html", {"app_name": "Global Setting - Taobility Software",})
        
application = webapp.WSGIApplication([
            (r'/admin/android/(.*)', AndroidAppHandler), 
            (r'/admin/iphone/(.*)', IphoneAppHandler), 
            (r'/admin/screen/(.*)', ScreenHandler), 
            ('/admin/addapp.*', AddAppHandler),                        
            ('/admin/setting', SettingHandler),
            ('/admin/apps', AppsHandler),
            ('/admin.*', DefaultHandler),
            ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()